#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Log.hpp"

//  对套接字的功能进行封装
enum 
{
    Socket_Err = 1,
    Bind_Err,
    Listen_Err,
    Accept_Err
};


class Socket
{
public:
    void Init()
    {
        // 创建套接字
        sockfd_ = socket(AF_INET , SOCK_STREAM , 0);
        if(sockfd_ < 0)
        {
            lg_(Fatal , "socket fail  , errno : %d , error messsge : %s " , errno , strerror(errno));
            exit(Socket_Err);
        }
    }
    void Bind(const std::string ip , const uint16_t port)
    {
        struct sockaddr_in client;
        client.sin_family = AF_INET;
        client.sin_port = htons(port);
        inet_aton(ip.c_str() , &(client.sin_addr));
        if(bind(sockfd_ , (sockaddr*)&client , sizeof(client)))
        {
            lg_(Fatal , "bind fail  , errno : %d , error messsge : %s " , errno , strerror(errno));
            exit(Bind_Err);
        }
    }
    void Listen()
    {
        if(listen(sockfd_ ,0) < 0)
        {
            lg_(Fatal , "listen fail  , errno : %d , error messsge : %s " , errno , strerror(errno));
            exit(Listen_Err);
        }
    }
    void Connect(const std::string& ip , const uint16_t& port)
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        inet_aton(ip.c_str() , &(server.sin_addr));

        if(connect(sockfd_ , (sockaddr*)&server , sizeof(server)))
        {
            lg_(Warning , "listen fail  , errno : %d , error messsge : %s " , errno , strerror(errno));
        }
    }
    int Accept(std::string& clientip , uint16_t& clientport)
    {
        struct sockaddr_in client;
        unsigned int len = sizeof(client);
        int sockfd = accept(sockfd_ , (sockaddr*)&client , &len);
        if(sockfd < 0)
        {
            lg_(Fatal , "accept fail  , errno : %d , error messsge : %s " , errno , strerror(errno));
            exit(Accept_Err);
        }
        clientip = inet_ntoa(client.sin_addr);
        clientport = client.sin_port;

        return sockfd;
    }

    int Getsockfd()
    {
        return sockfd_;
    }

    ~Socket()
    {
        close(sockfd_);
    }
private:
    int sockfd_;
};

